#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time:2021/3/31 15:15
# @Author:ytq
# @File:log_util.py
# !/usr/bin/env python

import os.path
import logging.handlers

import datetime
import logging
import os


log_format_timestamp = '%Y.%m.%d-%H.%M.%S'
log_format_str = '[%(asctime).19s] %(process)d:%(levelname)s %(filename)s:%(lineno)d:%(funcName)s: %(message)s'
log_formatter = logging.Formatter(log_format_str)
log_default_path = None
# 单例
log = None


def log_init(level):
    global log
    if log:
        log.debug(f'use exist log {log}')
        return
    else:
        pass

    log = logging.getLogger(__name__)
    log.setLevel(level)

    # 输出控制台
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(log_formatter)
    log.addHandler(stream_handler)
    return log


def set_log_level(level):
    """
    设置log级别, 10 ~ 50 区间
    :param level:
    :return:
    """
    log.setLevel(level)


def log_to_file(path=None):
    global log_default_path

    if log_default_path is not None:
        global log
        log.debug(f'use log {log_default_path}')
        return
    log = logging.getLogger(__name__)
    if path:
        log_path = path
    else:
        log_default_path = os.sep.join(['.', f"/logs/apiRestful.{datetime.datetime.now().strftime('%Y-%m-%d')}.log"])
        log_path = log_default_path

    file_handler = logging.FileHandler(log_path, encoding='utf-8')
    # 输出格式
    file_handler.setFormatter(log_formatter)
    # 绑定handler
    log.addHandler(file_handler)
    log.debug(f'log init {log_path}')


log_init(logging.DEBUG)
log = logging.getLogger(__name__)
log_to_file()
